package fy.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * 重新加载类
 * 
 * @author Administrator
 * 
 */
public class MyClassReLoader extends ClassLoader {

	private String className;

	public void setClassName(String className) {
		this.className = className;
	}

	public MyClassReLoader(ClassLoader parent) {
		super(parent);
	}

	public Class loadClass(String name) throws ClassNotFoundException {
		if (className == null || !className.equals(name)) {
			return super.loadClass(name);
		}
		try {
			String path = MyUtil.getRealPath(name);
			String url = "file:" + path.substring(1, path.length()) + ".class";
			System.out.println(url);
			URL myUrl = new URL(url);
			URLConnection connection = myUrl.openConnection();
			InputStream input = connection.getInputStream();
			ByteArrayOutputStream buffer = new ByteArrayOutputStream();
			int data = input.read();

			while (data != -1) {
				buffer.write(data);
				data = input.read();
			}

			byte[] classData = buffer.toByteArray();
			input.close();
			Class clazz = super.defineClass(name, classData, 0,
					classData.length);
			return clazz;

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public Class findClass(String name) throws ClassNotFoundException{
		return super.loadClass(name);
	}
}
